import { ref, computed } from 'vue'
import type { ChatMessage, UserProfile } from '../types/social'

export function useChatSystem() {
  const messages = ref<ChatMessage[]>([])
  const globalMessages = computed(() => messages.value.filter(m => m.to === null))
  const privateMessages = computed(() => messages.value.filter(m => m.to !== null))

  const sendMessage = async (
    content: string,
    to: UserProfile | null = null,
    type: 'text' | 'move' | 'emoji' | 'system' = 'text'
  ) => {
    try {
      const response = await fetch('/api/chat/send', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          content,
          to: to?.id,
          type
        })
      })

      if (!response.ok) {
        throw new Error('Failed to send message')
      }

      const message = await response.json()
      messages.value.push(message)
      return true
    } catch (error) {
      console.error('Error sending message:', error)
      return false
    }
  }

  const loadMessages = async (userId: string) => {
    try {
      const response = await fetch(`/api/chat/messages/${userId}`)
      if (!response.ok) {
        throw new Error('Failed to load messages')
      }

      const loadedMessages = await response.json()
      messages.value = loadedMessages
    } catch (error) {
      console.error('Error loading messages:', error)
    }
  }

  const loadGlobalMessages = async () => {
    try {
      const response = await fetch('/api/chat/global')
      if (!response.ok) {
        throw new Error('Failed to load global messages')
      }

      const loadedMessages = await response.json()
      messages.value = messages.value.filter(m => m.to !== null).concat(loadedMessages)
    } catch (error) {
      console.error('Error loading global messages:', error)
    }
  }

  const getPrivateChat = (userId: string) => {
    return messages.value.filter(m => 
      (m.from.id === userId && m.to !== null) || 
      (m.to?.id === userId)
    ).sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime())
  }

  const clearChat = (userId: string) => {
    messages.value = messages.value.filter(m => 
      m.from.id !== userId && m.to?.id !== userId
    )
  }

  const deleteMessage = async (messageId: string) => {
    try {
      const response = await fetch(`/api/chat/message/${messageId}`, {
        method: 'DELETE'
      })

      if (!response.ok) {
        throw new Error('Failed to delete message')
      }

      messages.value = messages.value.filter(m => m.id !== messageId)
      return true
    } catch (error) {
      console.error('Error deleting message:', error)
      return false
    }
  }

  return {
    messages,
    globalMessages,
    privateMessages,
    sendMessage,
    loadMessages,
    loadGlobalMessages,
    getPrivateChat,
    clearChat,
    deleteMessage
  }
} 